import type { ThemeModeType } from '@/stores/ChatStores/type';
import { useStores } from '@/stores/hooks';
import { isImageFilename } from '@/utils/util';
import type { SocketMessageType, ToolCallResult } from '@/utils/ws';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import Cookie from 'js-cookie';
import { observer } from 'mobx-react';
import React, { useEffect, useState } from 'react';
import useWebSocket from 'react-use-websocket';
import Chat from './components/Chat';
interface ConversationIds {
  userId: string;
  id: string;
}

const ChatWindow: React.FC = observer(() => {
  const { chatStores } = useStores();
  const [conversationIds] = useState<ConversationIds>();
  const { runAsync } = useRequest(chatStores.startChat, { manual: true });
  const { sendJsonMessage, lastMessage } = useWebSocket('ws://localhost:4000', {
    shouldReconnect: () => true,
    reconnectInterval: 3000,
  });
  useEffect(() => {
    if (lastMessage) handleSocketMessage(JSON.parse(lastMessage.data));
  }, [lastMessage]);
  const handleSocketMessage = (msg: SocketMessageType) => {
    const { type, data, id } = msg;
    switch (type) {
      case 'initialize': {
        const { sessionId } = data;
        console.log('🚀 ~ handleSocketMessage ~ sessionId:', sessionId);
        if (sessionId) Cookie.set('mcp-session-id', sessionId, { expires: 15 });
        break;
      }
      case 'toolCalls': {
        console.log(msg, 'msg');
        const toolCallRes: ToolCallResult[] = [];
        for (const tool of data) {
          const { id, function: func } = tool;
          if (!func) return;
          const { name, args } = func;
          console.log(name, 'id', args);
          if (name === 'changeBackground') {
            chatStores?.setBgColor(args.color);
          }
          if (name === 'changeTheme') {
            chatStores?.setTheme(args.theme as ThemeModeType);
            chatStores?.setBgColor('');
          }
          toolCallRes.push({ id, ok: true });
        }
        sendJsonMessage({
          type: 'toolCallsResult',
          id: id,
          data: toolCallRes,
        });
        chatStores?.setIsLoading(false);
        break;
      }
    }
  };

  // 使用axios发送POST请求示例
  const startStream = async (message: string) => {
    const response = await runAsync(message, conversationIds);
    console.log('🚀axios返回:', response);
    const data = response.text;
    chatStores?.setIsLoading(false);
    handlePostMessage(data);
  };
  // ==================== 消息处理 ====================

  const handlePostMessage = async (socketMessage: string) => {
    if (socketMessage) {
      if (isImageFilename(socketMessage)) {
        chatStores?.addContent({
          role: 'ASSISTANT',
          timestamp: dayjs().toDate(),
          content: socketMessage,
          id: Date.now().toString(),
          isImage: true,
        });
        return;
      }
      chatStores?.addContent({
        role: 'ASSISTANT',
        timestamp: dayjs().toDate(),
        content: '',
        id: Date.now().toString(),
      });
      const aiContents = chatStores?.aiMessages || [];
      const len = aiContents.length - 1;
      // ==================== 流输入 ====================
      for (let i = 0; i < socketMessage.length; i++) {
        await new Promise(i => setTimeout(i, 10));
        chatStores?.updateAiContent(len, socketMessage[i]);
      }
    }
  };
  const sendMessage = async (message: string) => {
    if (!message.trim()) return;
    console.log('准备发送消息:', message);
    startStream(message);
  };

  // ==================== 渲染 ====================
  return (
    <>
      <Chat onSendMessage={sendMessage} />
    </>
  );
});

export default ChatWindow;
